﻿#ifndef SDATAMODEL_H
#define SDATAMODEL_H

#include "IModelParser.h"
#include <QString>
#include <QDebug>

template <typename ModelType>
class SDataModel
{
public:
    explicit SDataModel() { m_isValid = false; m_parser = nullptr; }
    ~SDataModel();
    bool loadFromStr(const QString& jsonStr);
    void setModelData(const ModelType& data) { m_data = data; m_isValid = true; }
    void setModelParser(IModelParser<ModelType>* parser) { m_parser = parser; }

    bool isValid() const { return m_isValid; }
    QString toString(const ModelType& data) {  return m_parser ? m_parser->toString(data) : ""; }
    QString toString() {  return toString(m_data); }
    QString errorString() const { return m_parser ? m_parser->lastError() : QObject::tr("ModelParser not set."); }

    ModelType& data() { return m_data; }

    virtual ModelType emptyModelData() { return ModelType(); }

private:
    bool m_isValid;
    IModelParser<ModelType>* m_parser;
    ModelType m_data;
};

template<typename ModelType>
SDataModel<ModelType>::~SDataModel()
{
    if (m_parser) {
        delete m_parser;
        m_parser = nullptr;
    }
}

template<typename ModelType>
bool SDataModel<ModelType>::loadFromStr(const QString &jsonStr)
{
    if (!m_parser) {
        m_isValid = false;
        return false;
    }
    m_data = m_parser->loadFromString(jsonStr);
    if (!m_parser->lastError().isEmpty()) {
        m_isValid = false;
    } else {
        m_isValid = true;
    }
    return m_isValid;
}

#endif // SDATAMODEL_H
